package com.anyuan.wx.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.anyuan.wx.service.CoreService;
import com.anyuan.wx.util.SignUtil;

public class CoreServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    //校验
    public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
    	String signature = request.getParameter("signature");
    	String timestamp = request.getParameter("timestamp");
    	String nonce = request.getParameter("nonce");
    	String echostr = request.getParameter("echostr");
    	
    	PrintWriter out = response.getWriter();
    	if(SignUtil.checkSigature(signature, timestamp, nonce)){
    		out.print(echostr);
    	}
    	out.close();
    	out = null;
    }
    //处理微信服务器发来的消息
    public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
    	//TODO 消息的接收、处理和相应
    	request.setCharacterEncoding("UTF-8");
    	response.setCharacterEncoding("UTF-8");
    	
    	String signature = request.getParameter("signature");
    	String timestamp = request.getParameter("timestamp");
    	String nonce = request.getParameter("nonce");
    	
    	PrintWriter out = response.getWriter();
    	if(SignUtil.checkSigature(signature, timestamp, nonce))
    	{
    		String respXml = CoreService.processRequest(request);
    		out.print(respXml);
    	}
    	out.close();
    	out = null;
    	
    	
    	
    }
}
